package com.yvtian.admin.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yvtian.admin.pojo.SysUser;
import com.yvtian.admin.service.SysUserService;
import com.yvtian.admin.vo.UserInfoResponse;
import com.yvtian.admin.vo.UserVO;
import com.yvtian.annotation.Log;
import com.yvtian.annotation.PreAuthorize;
import com.yvtian.entity.Result;
import com.yvtian.entity.StatusCode;
import com.yvtian.enums.OperatorType;
import com.yvtian.exception.UserRegisteredException;
import com.yvtian.utils.DateUtils;
import com.yvtian.utils.StringHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Date;
import java.util.Map;

/**
 * @author long
 */
@Slf4j
@RestController
@RequestMapping(value = "/api/admin/user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @Log("查询用户的信息")
    @PreAuthorize(hasPermission = "admin:user:find")
    @RequestMapping(value = "/{userId}", method = RequestMethod.GET)
    public Result findById(@PathVariable String userId) {
        UserInfoResponse userInfo = sysUserService.findUserById(userId);
        return new Result(true, "查询成功", StatusCode.OK, userInfo);
    }

    @Log(value = "注册账号",isSave = true,operType = OperatorType.INSERT)
    @RequestMapping(value = "/reg", method = RequestMethod.POST)
    public Result register(@Valid @RequestBody SysUser sysUser) throws UserRegisteredException {
        sysUserService.register(sysUser);
        return new Result(true, "注册成功", StatusCode.OK);
    }

    @Log(value = "分页查询用户")
    @PreAuthorize(hasPermission = "admin:user:list")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Result findByPage(Page page,SysUser sysUser) {
        return new Result(true, "查询成功", StatusCode.OK, sysUserService.findByPage(page,sysUser));
    }

    @Log(value = "删除用户",isSave = true,operType = OperatorType.DELETE)
    @PreAuthorize(hasPermission = "admin:user:del")
    @RequestMapping(value = "/del", method = RequestMethod.POST)
    public Result delUser(@RequestBody Map<String, Object> map) {
        Result result = sysUserService.delUser(map);
        log.info("删除用户出参->{}", result);
        return result;
    }

    @Log(value = "更新用户信息",isSave = true,operType = OperatorType.UPDATE)
    @PreAuthorize(hasPermission = "admin:user:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public Result updateUser(@RequestBody SysUser sysUser) {
        if (sysUser.getId() == null){
            return new Result(false,"用户Id不能为空",StatusCode.PARAMS_IN_ERROR);
        }
        sysUserService.updateUser(sysUser);
        return new Result(true, "修改成功", StatusCode.OK);
    }

    @Log(value = "重置密码",isSave = true,operType = OperatorType.UPDATE)
    @PreAuthorize(hasPermission = "admin:user:restPwd")
    @RequestMapping(value = "/resetPwd/{id}",method = RequestMethod.POST)
    public Result restPassword(@PathVariable("id") String id) {
        if (StringHelper.isEmpty(id)) {
            return new Result(false, "用户id不能为空", StatusCode.PARAMS_IN_ERROR);
        }
        sysUserService.restPassword(id);
        return new Result(true, "修改成功", StatusCode.OK);
    }

    /**
     * 获取头像图片，返回Base64编码的字符串（实验的方法，图片一大就玩完）
     * @throws IOException
     */
    @Deprecated
    @RequestMapping(value = "/img/avatars/**")
    public Result getAvatar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String[] split = request.getRequestURI().split("/img");
        String path = this.getClass().getResource("/").getPath() + "static"+split[1] + ".jpg";
        File file = new File(path);
        System.out.println(file.exists());
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] b = new byte[fileInputStream.available()];
        fileInputStream.read(b,0,fileInputStream.available());
        Base64.Encoder encoder = Base64.getEncoder();
        String s = encoder.encodeToString(b);
        return new Result(true,"查询成功", StatusCode.OK,s);
    }

}
